var jude = Require(path.join(__dirname, 'verifty.js'));
// var optionSets = require('/component/optionSets');
var selectOptions = function(key, data, parent) {
    this.parent = parent;
    this.data = data;
    this.name = data[key];
    this.value = data[parent.options.setValueByDataKey];
    this.html = $('<div class="form_select_option ' + this.value + '">' + this.name + '</div>');
    this.selectStutas = false;
    var _this = this;
    this.html.unbind().bind('click', function() {
        _this.change();
    });
};
selectOptions.prototype = {
    constructor: this,
    render: function() {
        return this.html
    },
    select: function() {
        this.selectStutas = true;
        this.html.addClass('active');
        this.parent.name.text(this.name);
        this.parent.valueData = this.data;
        this.html.unbind();
    },
    removeSelect: function() {
        var _this = this;
        this.selectStutas = false;
        this.html.removeClass('active');
        this.html.unbind().bind('click', function() {
            _this.change();
        });
    },
    change: function() {
        if (this.parent.layout) {
            this.parent.layout.hideError();
        };
        for (var i = 0; i < this.parent.child.length; i++) {
            var element = this.parent.child[i];
            element.removeSelect();
        };
        this.select();
        this.parent.options.changeEvent(this.parent);

        if (jude.type(this.parent.relevance, 'function')) {
            this.parent.relevance();
        };
    }
};
var select = function(options, layout) {
    var _this = this;
    this.layout = layout;
    this.options = {
        className: '',
        type: 'select',
        jude: {
            name: '类型',
            rules: ['notNull']
        },
        showNameByDataKey: 'label',
        setValueByDataKey: 'value',
        getForm: 'id',
        "default": null,
        readonly: false,
        data: [],
        placeholder: '- 请选择 -',
        changeEvent: function(event) {}
    };
    this.options = $.extend({}, this.options, options);

    var html = '';
    html += '   <div class="form_select ' + (this.options.size ? this.options.size : '') + '">';
    html += '       <div class="form_select_nameBox">';
    html += '           <div class="form_select_name"></div>';
    html += '           <span></span>';
    html += '       </div>';
    html += '       <div class="form_select_optionBox"></div>';
    html += '   </div>';
    this._element = $(html);
    this.html = this._element;

    this.nameBox = this._element.find('.form_select_nameBox');
    this.name = this._element.find('.form_select_name');
    this.optionBox = this._element.find('.form_select_optionBox');
    var showOptionBox = false;
    var documentClick = function() {
        _this._element.removeClass('active');
        showOptionBox = false;
        _this.optionBox.css('display', 'none');
        $(document).unbind('click', documentClick);
    };
    this.nameBox.click(function(e) {
        e.stopPropagation();
        if (showOptionBox) {
            documentClick();
        } else {
            _this._element.addClass('active');
            showOptionBox = true;
            _this.optionBox.css('display', 'block');
            $(document).click();
            $(document).bind('click', documentClick);
        };
    });
    this.valueData = null;
    this.cache = null;

    this.setData(this.options.data);

    if (this.layout) {
        this.layout.append(this.html);
        if (this.options.className) {
            this.layout.html.addClass(this.options.className);
        };
    } else {
        if (this.options.className) {
            this.html.addClass(this.options.size);
            this.html.addClass(this.options.className);
        };
    };
    this.relevance = null;
};
select.prototype = {
    constructor: this,
    render: function() {
        return this.html
    },
    get: function(callBack) {
        if (this.valueData === null) {
            if (this.options.jude.rules[0] == 'notNull') {
                if (this.layout) {
                    this.layout.showError('请选择' + this.options.jude.name);
                };
                callBack('请选择' + this.options.jude.name);
            } else {
                callBack(false, null);
            }
        } else {
            if (this.options.getForm == 'object') {
                callBack(false, this.valueData);
            } else if (this.options.getForm == 'setValueByDataKey') {
                callBack(false, this.valueData[this.options.setValueByDataKey]);
            } else if (this.valueData.hasOwnProperty(this.options.getForm)) {
                callBack(false, this.valueData[this.options.getForm]);
            };
        };
    },
    set: function(data, doChange) {
        if (data === 'null') {
            return;
        };
        try {
            for (var i = 0; i < this.child.length; i++) {
                var element = this.child[i];
                element.removeSelect();
            };
            if (jude.type(data, 'number')) {
                if (this.child[data]) {
                    this.child[data].select();
                } else {
                    return
                };
            } else if (jude.type(data, 'string')) {
                var isComplete = false;
                for (var i = 0; i < this.child.length; i++) {
                    var element = this.child[i];
                    if (element.data[this.options.setValueByDataKey] == data) {
                        if (doChange) {
                            element.select();
                            element.change();
                        } else {
                            element.select();
                        };
                        isComplete = true;
                    }
                };
                if (!isComplete) {
                    return
                };
            } else if (jude.type(data, 'array')) {
                this.setData(data);
            } else if (jude.type(data, 'object')) {
                var isComplete = false;
                for (var i = 0; i < this.child.length; i++) {
                    var element = this.child[i];
                    if (jude.isEqual(data, element.data)) {
                        if (doChange) {
                            element.change();
                        } else {
                            element.select();
                        };
                        isComplete = true;
                        break;
                    }
                };
                if (!isComplete) {
                    return
                };
            };
        } catch (error) {
            this.cache = data;
        };
    },
    setData: function(data) {
        var _this = this;
        if (jude.type(data, 'string')) {
            console.log('暂时作废');

            // var optionsName = data.split(':');
            // if (optionsName[1]) {
            //     optionSets(optionsName[1], function (result) {
            //         _this.setData(result);
            //         _this.defaultValue();
            //         if (_this.cache !== null) {
            //             _this.set(_this.cache);
            //         };
            //     }, 'list');
            // };
        } else {
            this.data = data;
            this.child = [];
            this.optionBox.empty();
            this.valueData = null;
            this.options.data = data;
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                var child = new selectOptions(this.options.showNameByDataKey, item, this);
                this.child.push(child);
                this.optionBox.append(child.render());
            };
            this.defaultValue();
            if (jude.type(this.relevance, 'function')) {
                this.relevance();
            };
        };
    },
    defaultValue: function() {
        if (this.options['default'] === null) {
            this.name.text(this.options.placeholder);
        } else {
            this.set(this.options['default']);
        };
    },
    bindRelevance: function(event, dataKey) {
        var _this = this;
        this.relevance = function() {
            if (_this.valueData === null) {
                event.setData([]);
            } else {
                event.setData(_this.valueData[dataKey]);
            }
        }
    }
};
module.exports = function(options, layout) {
    return new select(options, layout);
};